import json
import os
from typing import Dict, Any
from pathlib import Path


class Storage:
    """数据存储工具类"""
    
    def __init__(self, data_dir: str = "data", filename: str = "tasks.json"):
        self.data_dir = Path(data_dir)
        self.filepath = self.data_dir / filename
        self._ensure_data_dir()
    
    def _ensure_data_dir(self):
        """确保数据目录存在"""
        self.data_dir.mkdir(exist_ok=True)
    
    def save(self, data: Dict[str, Any]) -> bool:
        """保存数据到文件"""
        try:
            with open(self.filepath, 'w', encoding='utf-8') as f:
                json.dump(data, f, ensure_ascii=False, indent=2)
            return True
        except Exception as e:
            print(f"保存数据失败: {e}")
            return False
    
    def load(self) -> Dict[str, Any]:
        """从文件加载数据"""
        try:
            if self.filepath.exists():
                with open(self.filepath, 'r', encoding='utf-8') as f:
                    return json.load(f)
            else:
                # 如果文件不存在，返回空的数据结构
                return {'tasks': []}
        except Exception as e:
            print(f"加载数据失败: {e}")
            return {'tasks': []}
    
    def backup(self, backup_suffix: str = ".backup") -> bool:
        """备份当前数据文件"""
        try:
            if self.filepath.exists():
                backup_path = self.filepath.with_suffix(self.filepath.suffix + backup_suffix)
                import shutil
                shutil.copy2(self.filepath, backup_path)
                return True
            return False
        except Exception as e:
            print(f"备份数据失败: {e}")
            return False
    
    def exists(self) -> bool:
        """检查数据文件是否存在"""
        return self.filepath.exists()
    
    def get_file_size(self) -> int:
        """获取数据文件大小（字节）"""
        try:
            if self.filepath.exists():
                return self.filepath.stat().st_size
            return 0
        except Exception:
            return 0
    
    def clear(self) -> bool:
        """清空数据文件"""
        try:
            if self.filepath.exists():
                self.filepath.unlink()
            return True
        except Exception as e:
            print(f"清空数据失败: {e}")
            return False